const http = require('http');
const https = require('https');
const fs = require('fs');
const axios = require('axios');
const path = require('path');

// 端口号
const PORT = 3000;

// 创建服务器
const server = http.createServer((req, res) => {
    console.log(req.url);

    if (req.method === 'GET' && req.url.indexOf("kFSwbTX0")!==-1) {
        const filePath = path.join(__dirname, './6.js');
        fs.readFile(filePath, 'utf8', (err, data) => {
            if (err) {
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.end('Internal Server Error');
                return;
            }
            res.writeHead(200, { 'Content-Type': 'application/javascript' });
            res.end(data);
        });
    } else {
        const targetUrl = `https://www.britishairways.com${req.url}`;
        const url = new URL(targetUrl);

        const options = {
            hostname: url.hostname,
            port: url.port || 443,
            path: url.pathname + url.search,
            method: req.method,
            headers: req.headers
        };

        const protocol = url.protocol === 'https:' ? https : http;

        const proxyReq = protocol.request(options, proxyRes => {
            res.writeHead(proxyRes.statusCode, proxyRes.headers);

            proxyRes.on('data', chunk => {
                res.write(chunk);
            });

            proxyRes.on('end', () => {
                res.end();
            });
        });

        proxyReq.on('error', error => {
            console.error('Error proxying request:', error);
            res.status(500).send('Internal Server Error');
        });

        if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
            req.pipe(proxyReq);
        } else {
            proxyReq.end();
        }
    }
});

// 监听端口
server.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`);
});
